<template>
  <div>
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>
<script>
import { addBatchEmployee } from '@/api/employees'// 批量增加员工
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
export default {
  components: { UploadExcelComponent },
  data() {
    return {

    }
  },
  methods: {
    async loadBatchEmployee(trans) {
      const res = await addBatchEmployee(trans)
      if (res.success) {
        this.$message({
          message: res.message,
          type: 'success'
        })
        this.$router.go(-1)
      } else {
        this.$message.error(res.data.message)
      }
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    }, // 你可以在上传之前做一些自己的特殊判断，如判断文件的大小是否大于 1 兆？若大于 1 兆则停止解析并提示错误信息。
    handleSuccess({ results, header }) {
      const trans = this.transExcel(results)
      this.loadBatchEmployee(trans)
      console.log(this.$router)
      // console.log('results', results)
      // console.log('header', header)
    }, // 解析成功时候会触发的回调函数，它会返回表格的表头和内容。
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      } // 先列一个枚举方变后面转换使用
      return results.map(zhObj => { // map方法返回一个处理好的对象
        const enObj = {}
        const zhKeys = Object.keys(zhObj)
        zhKeys.forEach(item => {
          if (mapInfo[item] === 'timeOfEntry' || mapInfo[item] === 'correctionTime') {
            enObj[mapInfo[item]] = new Date(formatExcelDate(zhObj[item]))
          } else {
            enObj[[mapInfo[item]]] = zhObj[item]
          }
        })
        return enObj
      })
    }// 将文件转换成后端需要的格式
  }
}
</script>
<style scoped>

</style>
